cc.Class({
    extends: cc.Component,

    properties: {

        //追号期数
        edCheseNum:{
            default:null,
            type:cc.EditBox
        },

        //期号列表
        tgCheseGroup:{
            default:[],
            type:cc.Toggle
        },

        //总共期数注数金额
        labBetInfo:{
           default: null,
           type: cc.Label 
        },

        //期数列表
        betConetent:{
           default: null,
           type: cc.Layout 
        },

        //列表item
        cartItem:{
            default: null,
            type: cc.Prefab
        },

        swCorll:cc.ScrollView,
        ndBetCart:cc.Node,
        chaseNumAnim:cc.Animation,//动画

        _betNumbers:[],//投注栏信息
        _chaseAnimState:false,//动画状态
        _isStops:-1,//追号到截止
        _lotteryID:0,//彩种id
        _betNums:0,//号码栏item标识
        _allBet:null,//总投注统计
        _curPageCallBack:null,//回调界面
    },

    // use this for initialization
    onLoad: function () {
        this.node.on(cc.Node.EventType.TOUCH_END, function (event) {
            console.log('betcartpage node  TOUCH_END');
            var contentRect = this.ndBetCart.getBoundingBoxToWorld();
            contentRect.x = contentRect.x -20;
            contentRect.width = 1080;
            var touchLocation = event.getLocation();
            if(cc.rectContainsPoint(contentRect, touchLocation) == false){
                this.onClose();
            }
        }, this);

    },

    init :function(callback){
        this._allBet = new Object(); 
        this._allBet.Multiple = 1;//总倍数
        this._allBet.Bet = 0;//总注数
        this._allBet.Money = 0;//总金额
        this._allBet.chaseNum = 1;//追号期
        this._isStops = -1;
        this._betNums = 0;
        this._curPageCallBack = callback;
    },

    addBetNumber: function(data){
        var datainfo = data;
        var content = [];
        var playcode = data.dataBase.PlayCode
        this._lotteryID = data.lotteryId;
        content.push(LotteryUtils.getPlayTypeDecByPlayIdNor(data.dataBase.PlayCode,data.dataBase.isNorm));
        content.push(data.dataBase.Bet);
        content.push(data.dataBase.Multiple);
        content.push(data.money);
    
        this._betNums++;

        var item = cc.instantiate(this.cartItem);
        //清除事件
        item.getComponent('bet_cart_Item').init(data.dataBase.Number,content); 
        var clickEventHandler = new cc.Component.EventHandler();
        clickEventHandler.target = this.node; 
        clickEventHandler.component = "BetCartPage"
        clickEventHandler.handler = "onClickCallBack";
        clickEventHandler.customEventData = this._betNums;
        item.getChildByName("btnClose").getComponent(cc.Button).clickEvents.push(clickEventHandler);
        //重新选择事件
        var clickEventHandler1 = new cc.Component.EventHandler();
        clickEventHandler1.target = this.node; 
        clickEventHandler1.component = "BetCartPage"
        clickEventHandler1.handler = "onRetCallBack";
        clickEventHandler1.customEventData = {nums:datainfo,index:this._betNums,add:data.isAdd};
        item.getChildByName("btnRet").getComponent(cc.Button).clickEvents.push(clickEventHandler1);

        this.betConetent.node.addChild(item);
        if(this.betConetent.node.childrenCount>5)
            this.swCorll.scrollToBottom(0.1);
        
        var data = {
            ID:this._betNums,
            info:datainfo,
        } 
        this._betNumbers.push(data);
        this.showAllBet();
        
    },

    showAllBet: function(){
        this._allBet.Money = 0;
        this._allBet.Bet = 0;
        this._allBet.Multiple = 0;
        for(var i=0;i<this._betNumbers.length;i++)
        {
            this._allBet.Multiple += this._betNumbers[i].info.dataBase.Multiple;
            this._allBet.Bet += this._betNumbers[i].info.dataBase.Bet;
            this._allBet.Money += this._betNumbers[i].info.money;
        }

        this._allBet.Money = this._allBet.Money*this._allBet.chaseNum;
        this.labBetInfo.string = "共" + this._allBet.Money + "元   " + this._allBet.Bet+ "注"+this._allBet.chaseNum +"期";
    },

    retmoveOneItem:function(arry,val){
        for(var i=0; i<arry.length; i++) {
            if(arry[i].ID == val) {
                arry.splice(i, 1);
                return true;
            }
        }
        return false;
    },

    onClickCallBack:function(event, customEventData){
        if(this.retmoveOneItem(this._betNumbers,customEventData))
        {
            cc.log("betcartpage 删除后数组长度：" +this._betNumbers.length);
            this.betConetent.node.removeChild(event.target.parent);
            this.showAllBet();
        }
        else
        {
            cc.log("betcartpage 删除数组失败");
        }
    },

    onRetCallBack:function(event, customEventData){
        var numsArry = customEventData.nums.dataBase.Number.split("|");
        var numsArrys = [];
        if(numsArry.length>1)
        {
            numsArrys.push(numsArry[0]);
            numsArrys.push(numsArry[1]);
        }
        else
        {
            return;
        }

        if(this.retmoveOneItem(this._betNumbers,customEventData.index))
        {
            cc.log("betcartpage 删除后数组长度：" +this._betNumbers.length);
            this.betConetent.node.removeChild(event.target.parent);
            this.showAllBet();
            this.onContinue();
            this._curPageCallBack.autoSelNums(customEventData.nums.dataBase.Multiple,customEventData.nums.dataBase.isNorm,customEventData.add,numsArrys);
        }
        else
        {
            cc.log("betcartpage 删除数组失败");
        }
    },

    //设置追号数
    setCheseNum:function(CheseNum){
        var num = parseInt(CheseNum);
        if(num >154)
        {
            num = 154;
            ComponentsUtils.showTips("最大只能追154期");
        }
         this.edCheseNum.string = num.toString();
         this._allBet.chaseNum = num;

    },

    //获取当前期数
    getCheseNum:function(){
        var amount = parseInt(this.edCheseNum.string);
        if(isNaN(amount)){ 
            return 1;
        }else{
            return amount;
        }        
    },

    //清理期号选择
    cleanCheseSelect:function(){
        for(var i = 0;i<this.tgCheseGroup.length;i++)
        {
            this.tgCheseGroup[i].getComponent(cc.Toggle).isChecked= false;
        }
    },

    //期数显示播放
    playCheseAni:function(){
        if(this.getCheseNum() > 1)
        {
            if(!this._chaseAnimState)
            {   
                this._chaseAnimState = true;
                this.chaseNumAnim.play("ani_betchase_out");
                this.cleanCheseSelect();
                
            }
        }
        else
        {
            if(this._chaseAnimState)
            {
                this._chaseAnimState = false;
                this.chaseNumAnim.play("ani_betchase_in");
            }   
        }
    },

    //手动输入期数
    onCheseTextChanged:function(editbox){
        if(!Utils.isInt(editbox.string))
        {
            //ComponentsUtils.showTips("输入格式错误！");
            editbox.string = "1";
        }
        if(editbox.string == null || editbox.string == "")
        {
            editbox.string = "1";
        }
        var amount = parseInt(editbox.string);
        if(isNaN(amount) || amount > 999 || amount<=0 ){
            editbox.string = "1";
            amount = 1;
        }

        this.cleanCheseSelect();
        this.setCheseNum(editbox.string);
        this.playCheseAni();
        this.showAllBet();
    },

    //选择期数
    onToggleCheck:function(toggle, customEventData) {
        this.setCheseNum(customEventData.toString());
        this.showAllBet();
    },

    //继续选号
    onContinue:function(){
        this.playCheseAni();
        this.node.active = false;
    },

    //随机选
    onAnySelectBet:function(event,customEventData){
        this._curPageCallBack.randomAnySelect(customEventData) ;
    },

    //是否中奖后停止追号
    onIsStops:function(toggle, customEventData){
        if(toggle.isChecked == true)
        {
            this._isStops = 0;
        }
        else
        {
            this._isStops = -1;
        }
    },

    //组合基础投注
    dataToJson:function(){
        var obj1 = new Object(); 
        var obj2 = new Object(); 

        var objs = [];
        var arry1 = [];
        var arry2 = [];

        var tempcode = "";
        for(var i=0;i<this._betNumbers.length;i++)
        { 
            if(this._betNumbers[i].info.dataBase.PlayCode == "90102")
            {
                obj1.PlayCode = this._betNumbers[i].info.dataBase.PlayCode; 
                var numArrays = {
                    "Multiple":this._betNumbers[i].info.dataBase.Multiple,
                    "Bet":this._betNumbers[i].info.dataBase.Bet,
                    "isNorm":this._betNumbers[i].info.dataBase.isNorm,
                    "Number": this._betNumbers[i].info.dataBase.Number
                };
                arry1.push(numArrays);
            }
            else
            {
                obj2.PlayCode = this._betNumbers[i].info.dataBase.PlayCode; 
                var numArrays = {
                    "Multiple":this._betNumbers[i].info.dataBase.Multiple,
                    "Bet":this._betNumbers[i].info.dataBase.Bet,
                    "isNorm":this._betNumbers[i].info.dataBase.isNorm,
                    "Number": this._betNumbers[i].info.dataBase.Number
                };
                arry2.push(numArrays);
            } 
        }
        obj1.Data = arry1.length >0 ? arry1 : null;
        obj2.Data = arry2.length >0 ? arry2 : null;
         
        if(obj1.Data != null )
        {
            JSON.stringify(obj1);
            objs.push(obj1);
        }
        if(obj2.Data != null )
        {
            JSON.stringify(obj2);
            objs.push(obj2);
        }   

        var json = JSON.stringify(objs);
        cc.log("提交订单：" + json);
        return json;
    },

    //追号组合支付
    chasePay:function(){
        var recv = function(ret){
            ComponentsUtils.unblock(); 
            if(ret.Code === 0)
            {
                var len = ret.Data.length;
                if(len != this.getCheseNum())
                {
                    this.setCheseNum(len);
                    this.showAllBet();
                }
                var obj = new Object(); 
                obj.Stops = this._isStops;
                obj.IsuseCount = len;
                obj.BeginTime = ret.Data[0].BeginTime;
                obj.EndTime = ret.Data[len-1].EndTime;
                var arry = [];
                for(var i=0;i<ret.Data.length;i++)
                {
                    var numArrays = {
                        "IsuseID":ret.Data[i].IsuseCode,
                        "Amount": LotteryUtils.moneytoClient(this._allBet.Money/this._allBet.chaseNum),//每期金额
                        "Multiple":this._allBet.Multiple,//每期总倍数
                    };
                    arry.push(numArrays);
                }
                obj.Data = arry;
                var json = JSON.stringify(obj);

                var data = {
                    lotteryId:this._lotteryID,//彩种id
                    dataBase:this.dataToJson(),//投注信息
                    otherBase:json,//追号
                    money:this._allBet.Money, 
                    buyType: this._allBet.chaseNum >1?1:0,//追号
                }
                
                window.Notification.emit("BET_ONPAY",data);
                this._curPageCallBack.onClose();
            }
            else
            {
                ComponentsUtils.showTips(ret.Msg);
            }
        }.bind(this);
        var data = {
            Token:User.getLoginToken(),
            LotteryCode:this._lotteryID,
            Top:this.getCheseNum(),
        }
        CL.HTTP.sendRequest(DEFINE.HTTP_MESSAGE.GETADDTOISUSE, data, recv.bind(this),"POST");   
        ComponentsUtils.block();    
    },

    //是否存在投注列表
    isHasBetNumbers:function(){
         if(this._betNumbers.length<=0 || this._allBet.Money <= 0)
        {
            return false;
        }
        else
        {
            return true;
        }
    },
    //支付
    onPay:function(){
        if(this._betNumbers.length<=0 || this._allBet.Money <= 0)
        {
            ComponentsUtils.showTips("没有投注信息!");
            return;
        }
        if(this.getCheseNum()<=1)
        {
            var data = {
                lotteryId:this._lotteryID,//彩种id
                dataBase:this.dataToJson(),//投注信息
                otherBase:"",//追加
                money:this._allBet.Money, 
                buyType: this._allBet.chaseNum >1?1:0,//追号
            }
            window.Notification.emit("BET_ONPAY",data);
        }
        else
        {
            this.chasePay();
        }
    },
    
    onClose:function(){
        var confirmCallback = function(){
            this._curPageCallBack.onClose();
        }.bind(this);
        var closeCallback = function(){
            cc.log("closeCallback");
        }.bind(this);
        ComponentsUtils.showAlertTips(2, "退出将清除所有选号，是否退出？", closeCallback, "退出提示", confirmCallback);          
    }

});
